package cn.itcast.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class HttpClientUtil {

    private static CloseableHttpClient client;
    static {
     // 构建连接池管理器对象
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        cm.setMaxTotal(20);
        // 设置每个主机地址的并发数
        cm.setDefaultMaxPerRoute(15);

        // 构建请求配置信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(3000) // 创建连接的最长时间
                .setConnectionRequestTimeout(1000) // 从连接池中获取到连接的最长时间
                .setSocketTimeout(1000) // 数据传输的最长时间
                .setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
                .build();

        // 构建HttpClient对象,把连接池、请求配置对象作为参数
        client = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config)
                .build();
    }
    
    public static String doGet(String uri){
        HttpGet get = new HttpGet(uri);
        try {
            return client.execute(get, new BasicResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
